package ui.windows;

import entities.User;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import manager.GenericDriver;
import model.ChoseUserTableModel;

/**
 * 
 * @author viev
 * 
 */
public class UserChooserDialog extends javax.swing.JDialog {

    /** Creates new form UserChooserDialog */
    public UserChooserDialog(RemedySchedulerFrame mainFrame) {
        this.mainFrame = mainFrame;
        driver = mainFrame.getGenericDriver();
        initComponents();
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public void showUserChooser(int choiseModel) {
        if (choiseModel >= 1 && choiseModel <= 5) {
            selected = false;
            switch (choiseModel) {
                case 1:
                    includeModelMode1();
                    break;
                case 2:
                    includeModelMode2();
                    break;
                case 3:
                    includeModelMode3();
                    break;
                case 4:
                    includeModelMode4();
                    break;
                case 5:
                    includeModelMode5();
                    break;
            }
            this.setVisible(true);
        }
    }

    public User getUser() {
        if (selected) {
            return selectedUser;
        } else {
            return null;
        }
    }

    private void includeModelMode1() {
        model = new ChoseUserTableModel(driver.showUser(), ChoseUserTableModel.SELECT_ALL_MODE);
        userTable.setModel(model);
        userTable.setFillsViewportHeight(true);
    }

    private void includeModelMode2() {
        model = new ChoseUserTableModel(driver.showHead(), ChoseUserTableModel.SELECT_HEAD_MODE);
        userTable.setModel(model);
        userTable.setFillsViewportHeight(true);
        userTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer();
        cellRenderer.setBackground(Color.yellow);
        userTable.getTableHeader().setFont(new Font(null, Font.BOLD, 11));
        userTable.getColumnModel().getColumn(0).setPreferredWidth(100);
        userTable.getColumnModel().getColumn(1).setPreferredWidth(200);
        userTable.getColumnModel().getColumn(2).setPreferredWidth(200);
        userTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        userTable.getColumnModel().getColumn(3).setCellRenderer(cellRenderer);
        int count = model.getRowCount();
        if(count == 0) {
            lbMessage.setText("(empty)");            
        } else {
            lbMessage.setText("(" + count + " rows)");
        }
    }

    private void includeModelMode3() {
    }

    private void includeModelMode4() {
    }

    private void includeModelMode5() {
        model = new ChoseUserTableModel(driver.showEmployeeByDID(mainFrame.getUser().getDepartmentID()), ChoseUserTableModel.SELECT_EMPLOYEE_OF_DEPARTMENT_MODE);
        userTable.setModel(model);
        userTable.setFillsViewportHeight(true);
    }

    private void setSelectedUser(java.awt.event.MouseEvent evt) {
        int index = userTable.getSelectedRow();
        if (index != -1) {
            selectedUser = model.getAt(index);
            if(evt.getClickCount() == 2) {
                setSelected();
            }
            bChose.setEnabled(true);
        } else {
            selectedUser = null;
            bChose.setEnabled(false);
        }
    }

    private void setSelected() {
        selected = true;
        close();
    }

    private void filter() {
        model.filter(txtID.getText(), txtName.getText(), 0, 0, 0);
        int count = model.getRowCount();
        if(count == 0) {
            lbMessage.setText("(empty)");            
        } else {
            lbMessage.setText("(" + count + " rows)");
        }
    }

    private void close() {
        this.setVisible(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtID = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        lbMessage = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        bClose = new javax.swing.JButton();
        bChose = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        userTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Chose User");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(0, 51, 51));

        jLabel1.setForeground(new java.awt.Color(204, 255, 204));
        jLabel1.setText("ID:");

        txtID.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtIDCaretUpdate(evt);
            }
        });

        jLabel2.setForeground(new java.awt.Color(204, 255, 204));
        jLabel2.setText("Name:");

        txtName.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                txtNameCaretUpdate(evt);
            }
        });

        lbMessage.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lbMessage.setForeground(new java.awt.Color(255, 255, 51));
        lbMessage.setText("value");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(lbMessage)
                .addContainerGap(283, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbMessage))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);

        jPanel2.setBackground(new java.awt.Color(0, 51, 51));

        bClose.setText("Close");
        bClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCloseActionPerformed(evt);
            }
        });

        bChose.setText("Chose");
        bChose.setEnabled(false);
        bChose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bChoseActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(485, Short.MAX_VALUE)
                .addComponent(bChose, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bClose, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bClose)
                    .addComponent(bChose))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);

        userTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        userTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                userTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(userTable);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void txtIDCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtIDCaretUpdate
    filter();
}//GEN-LAST:event_txtIDCaretUpdate

private void txtNameCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtNameCaretUpdate
    filter();
}//GEN-LAST:event_txtNameCaretUpdate

private void userTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_userTableMouseClicked
    setSelectedUser(evt);
}//GEN-LAST:event_userTableMouseClicked

private void bChoseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bChoseActionPerformed
    setSelected();
}//GEN-LAST:event_bChoseActionPerformed

private void bCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCloseActionPerformed
    close();
}//GEN-LAST:event_bCloseActionPerformed

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
}//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UserChooserDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UserChooserDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UserChooserDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UserChooserDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                UserChooserDialog dialog = new UserChooserDialog(new RemedySchedulerFrame());
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    private RemedySchedulerFrame mainFrame;
    private GenericDriver driver;
    private ChoseUserTableModel model;
    private User selectedUser;
    private boolean selected;
    public static int SELECT_ALL_MODE = 1;
    public static int SELECT_HEAD_MODE = 2;
    public static int SELECT_HEAD_AND_EMPLOYEE_MODE = 3;
    public static int SELECT_ALL_EMPLOYEE_MODE = 4;
    public static int SELECT_EMPLOYEE_OF_DEPARTMENT_MODE = 5;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bChose;
    private javax.swing.JButton bClose;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbMessage;
    private javax.swing.JTextField txtID;
    private javax.swing.JTextField txtName;
    private javax.swing.JTable userTable;
    // End of variables declaration//GEN-END:variables
}
